#!/bin/bash

run() {
  local base_command_path=$1
  local base_plugin_get_path=$2
  local command=$3
  local sub_command=$4

  # register plugins commands
  # plugin::register_all $base_plugin_get_path

  log::debug ""
  log::debug "[$(timestamp)][command] base command path: $base_command_path"
  log::debug "[$(timestamp)][command] run: ${@:3}"
  log::debug "[$(timestamp)][command]"

  # Use Help Command
  if [ "$sub_command" = "help" ]; then
    help $base_command_path $command ${@:4} # $sub_command
    exit 1
  fi

  # command_path=$(commander::get_command_path $@)
  # if [ "$?" != "0" ]; then
  if ! commander::has_command_path "$@"; then
    local commands=${@:3}
    # DEBUG
    log::debug "[$(timestamp)][command]"
    log::debug "[$(timestamp)][command] command: $commands"

    # Help
    if [ "$command" != "" ]; then
      # zmicro -v
      if [ "$command" = "-v" ]; then
        zmicro version
        exit 0
      fi

      if [ "$commands" != "-h" ] && [ "$commands" != "--help" ]; then
        echo -e "No such command: $(color::red $commands). use --help for help" | tee -a $ZMICRO_LOG_ERROR_PATH
        echo ""
      fi
    fi

    help $base_command_path $commands
    exit 1
  fi

  # Get Command
  log::debug "[$(timestamp)][command]"
  log::debug "[$(timestamp)][command] get command path start ..."
  command_path=$(commander::get_command_path $@)

  log::command "$command_path"
}

run::js() {
  local script=$1
  if [ -z "$script" ]; then
    log::error "js script is required"
    exit 1
  fi

  load_nvm() {
    local NVM_DIR=$HOME/.nvm
    if [ -s "$NVM_DIR/nvm.sh" ]; then
      . "$NVM_DIR/nvm.sh" # This loads nvm
    fi
  }

  is_nodejs_installed() {
    load_nvm

    which node >>/dev/null 2>&1
    if [ "$?" = "0" ]; then
      echo "true"
    else
      echo "false"
    fi
  }

  if [ "$(is_nodejs_installed)" = "false" ]; then
    zpackage install nodejs
  fi

  load_nvm

  # @TODO
  if [ "$(net::is_google_visitable)" = "false" ]; then
    export NPM_CONFIG_REGISTRY=https://registry.npm.taobao.org
  fi

  node $@
}

export -f run
export -f run::js
